const {
  Orders
} = require('../models/ordersModel');
const {
  Salesmans
} = require('../models/salesmansModel');
const {
  Claims
} = require('../models/claimsModel');



//获取数据
async function getAllClaims(req, res, next) {
  let data = await Claims
    .find()
    .populate({
      path: "ordersId",
      populate: {
        path: 'productsId'
      },
      // populate: {
      //     path: 'salesmanId'
      // }
    }) //关联
    .populate("salesmanId") //关联


  res.send({
    status: 1,
    data,
    message: '所有数据获取成功'
  });
}

async function deleteOneClaim(req, res) {
  const { _id } = req.body;
  await Claims.findByIdAndDelete(_id);
  res.send({
    status: 1,
    message: '删除信息成功',
  })
};

async function changeStatus(req, res) {
  const { _id, state } = req.body;
  const data = await Claims.updateOne({ _id }, { state });
  if (data.nModified == 1) {
    res.send({
      status: 1,
      message: '修改成功'
    })
  } else {
    res.send({
      status: 0,
      message: '修改失败'
    })

  }
};
//新增理赔单
async function AddOneByApply(req, res) {
  const { ordersId, stareTime, salesmanId, reason, img, state } = req.body;
  const data = await Claims.create({ ordersId, stareTime, salesmanId, reason, img, state });
  // 移动图片 
  if (imgURL) {
    moveFiles({
      fromPath: './public/temp',
      toPath: './public/images',
      filename: imgURL
    });
    removeFiles('./public/temp');
  }
  res.send({
    status: 1,
    message: '新增理赔单成功',
  });
}

async function getOneClaim(req, res) {
  const { _id } = req.body;
  const data = await Claims.findById({ _id });
  console.log(data);
  res.send({
    status: 1,
    data,
    message: '所有数据获取成功'
  })
}

async function updateOneClaim(req, res) {
  const { _id, reason, img } = req.body;
  const data = await Claims.updateOne({ _id }, { img, reason });
  if (data.nModified == 1) {
    res.send({
      status: 1,
      message: '修改理赔成功',
    });
  } else {
    res.send({
      status: 0,
      message: '修改理赔失败',
    });
  }
}


module.exports = {
  getAllClaims,
  deleteOneClaim,
  changeStatus,
  AddOneByApply,
  getOneClaim,
  updateOneClaim
};